//
//  NetManager.swift
//  HuaYun
//
//  Created by enghou on 2018/6/27.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

import Alamofire

let NETCHANGED = "NetChanged"

let NETSHUTDOWN = "NETSHUTDOWN"

class NetManager: NSObject {
    
    static func add()->Void{
        
        NetworkReachabilityManager.init(host: Server)?.listener = {state in
            NotificationCenter.default.post(name: NSNotification.Name.init(NETCHANGED), object: state)
        }
    }
    
    static var netstate: NetworkReachabilityManager.NetworkReachabilityStatus{
        get{
            return NetworkReachabilityManager.init(host: Server)?.networkReachabilityStatus ?? .notReachable
        }
    }
    
    static var isActive: Bool{
        get{
            return NetworkReachabilityManager.init(host: Server)?.isReachable ?? false
        }
    }
    
    static func post(_ path: String,_ param: Param?,suc: NetSuccess?,fail: NetFail?)->Void{
        
        guard path.count != 0 else {
            
            let result = ["success":false,"errorMsg":"路径为空"] as [String : Any]
            
            suc?(JSON(result))
            
            return
        }
        
        let absolutePath = Server + path
        
        guard let url = URL.init(string: absolutePath) else { return  }
        
        Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result {
            case .success(let result):
                let json = JSON(result)
                suc?(json)
            case .failure(let error):
                fail?(error)
            }
        }
    }
    
    static func get(_ path: String,_ param: Param?,suc: NetSuccess?,fail: NetFail?)->Void{
        
        guard path.count != 0 else {
            let result = ["success":false,"errorMsg":"路径为空"] as [String : Any]
            suc?(JSON(result))
            return
        }
        
        if path == GETORG {
            suc?(JSON(["success": true,"code": 2000,"data": [["name":"浙江华云信息科技有限公司","code": "x"],["name":"智慧电力集成运维分公司","code": "x11x"],["name":"信息通信事业部","code": "x12x"],["name":"数据应用事业部","code": "x13x"],["name":"技术研究中心","code": "x14x"],["name":"双创公司","code": "x15x"]]]))
            return
//            let org = User.orgCode
//            if User.isLeader {
//
//            }
//            switch org{
//            case "x11x":
//                suc?(JSON(["success": true,"code": 2000,"data": [["name":"智慧电力集成运维分公司","code": org]]]))
//                return
//            case "x12x":
//                suc?(JSON(["success": true,"code": 2000,"data": [["name":"信息通信事业部","code": org]]]))
//                return
//            case "x13x":
//                suc?(JSON(["success": true,"code": 2000,"data": [["name":"数据应用事业部","code": org]]]))
//                return
//            case "x14x":
//                suc?(JSON(["success": true,"code": 2000,"data": [["name":"技术研究中心","code": org]]]))
//                return
//            case "x15x":
//                suc?(JSON(["success": true,"code": 2000,"data": [["name":"双创公司","code": org]]]))
//                return
//            default:
//                fail?(NSError.init(domain: "Permission Denied", code: -1, userInfo: nil))
//                return
//            }
        }
        
        let absolutePath = Server + path
        
        guard let url = URL.init(string: absolutePath) else { return  }
        
        Alamofire.request(url, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result {
            case .success(let result):
                let json = JSON(result)
                suc?(json)
            case .failure(let error):
                fail?(error)
            }
        }
    }
    
    static func upload(_ path: String,_ param: Param?,_ files: Array<Data>,name: String,suc: NetSuccess?,fail: NetFail?)->Void{
        guard path.count != 0 else {
            let result = ["success":false,"errorMsg":"路径为空"] as [String : Any]
            suc?(JSON(result))
            return
        }
        
        let absolutePath = Server + path
        
        guard let url = URL.init(string: absolutePath) else { return  }
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            var idx = 0
            for dt in files {
                idx = idx + 1
                let time = Date.init().dateStr + "iOS" + String(idx)
                let fileName =  time.md5 + ".jpg"
                multipartFormData.append(dt, withName: name, fileName: fileName, mimeType: "image/png")
            }
        }, usingThreshold: 5*1024*1024, to: url, method: .post, headers: ["Content-Type":"application/json;charset=UTF-8"]) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    
                    let result = response.result.value
                    
                    suc?(JSON(result ?? [:]))
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    static func download(path: String,prog: ((_ prog: CGFloat)->Void)?,done: ((_ u: URL?)->Void)?)->Void{
        
        guard let url = URL(string: path) else {
            
            return
            
        }
        
        Alamofire.download(URLRequest(url: url), to: DownloadRequest.suggestedDownloadDestination()).downloadProgress { (progress) in
            
            let total = progress.totalUnitCount
            
            let current = progress.completedUnitCount
            
            let percent = CGFloat(current) / CGFloat(total)
            
            prog?(percent)
            
            }.response { (response) in
                
                done?(response.destinationURL)
        }
    }
    
}
